<template>
	<view class="content">

		

    <view class="DrawerPage content" :class="modalName=='viewModal'?'show':''">
			
			
			<view class="cu-bar bg-gradual-blue ">
				<view class="cu-avatar round"  @tap="showModal" data-target="viewModal"><text  class="lg text-gray cuIcon-more" ></text></view>
				<view class="content">
					RSS订阅
				</view>
				
			</view>
			<view v-if="tabBars.length ==0" class="solids-bottom padding-xs flex align-center">
				
				<view class="flex-sub text-center">
					<view class="solid-bottom text-xsl padding">
						<text class=" cuIcon-emoji text-green"></text>
					</view>
					<view class="padding" @tap="nav2Add">去添加订阅，添加后请刷新本页面</view>
				</view>
			</view>
			<!-- 顶部选项卡 -->
			<scroll-view  v-if="tabBars.length !=0"  id="nav-bar" class="nav-bar" scroll-x scroll-with-animation :scroll-left="scrollLeft">
				<view v-for="(item,index) in tabBars" :key="item.id" class="nav-item" :class="{current: index === tabCurrentIndex}"
				 :id="'tab'+index" @click="changeTab(index)">{{item.name}}</view>
			</scroll-view>

			<!-- 下拉刷新组件 -->
			<mix-pulldown-refresh  v-if="tabBars.length !=0" ref="mixPulldownRefresh" class="panel-content" :top="90" @refresh="onPulldownReresh"
			 @setEnableScroll="setEnableScroll">
				<!-- 内容部分 -->
				<swiper id="swiper" class="swiper-box" :duration="300" :current="tabCurrentIndex" @change="changeTab">
					<swiper-item v-for="tabItem in tabBars" :key="tabItem.id">
						<scroll-view class="panel-scroll-box" :scroll-y="enableScroll" @scrolltolower="loadMore">
						
							<view class="cu-card article" v-for="(item, index) in tabItem.newsList" :key="index" @click="navToDetails(item)">

								<view class="cu-item shadow">
									<view class="title"><view class="text-cut">{{item.title}}</view></view>
									<view class="content">
									
										<view class="desc">
											<view class="text-content">{{item.txt}} </view>
											<view>
												
												<view class="cu-tag bg-green light sm round" v-if="item.time">{{item.time}}</view>
											</view>
										</view>
									</view>
								</view>

							</view>


							<!-- 上滑加载更多组件 -->
							<mix-load-more :status="tabItem.loadMoreStatus"></mix-load-more>
						</scroll-view>
					</swiper-item>
				</swiper>
			</mix-pulldown-refresh>
			</view>
			<view class="DrawerClose " :class="modalName=='viewModal'?'show':''" @tap="hideModal">
				<text class="cuIcon-pullright"></text>
			</view>
			<scroll-view scroll-y class="DrawerWindow" :class="modalName=='viewModal'?'show':''">
				<view class="cu-list menu card-menu margin-top-xl margin-bottom-xl shadow-lg">
					<view class="cu-item arrow" @tap="nav2Add">
						<view class="content">
							<text class="cuIcon-add text-grey"></text>
							<text class="text-grey">添加订阅</text>
						</view>
					</view>
					<view class="cu-item arrow" @tap="tapRss">
						<view class="content">
							<text class="cuIcon-settings text-grey"></text>
							<text class="text-grey">管理订阅</text>
						</view>
					</view>
					
					<view class="cu-item arrow" @tap="backup">
						<view class="content">
							<text class="cuIcon-share text-grey"></text>
							<text class="text-grey">复制备份</text>
						</view>
					</view>
					
					
					<view class="cu-item arrow" @tap="nav2hot">
						<view class="content">
							<text class="cuIcon-hot text-grey"></text>
							<text class="text-grey">热榜</text>
						</view>
					</view>
					
					
				</view>
			</scroll-view>
		</view>
		
	</view>
</template>

<script>
	import help from '../../common/help.js'
	import mixPulldownRefresh from '@/components/mix-pulldown-refresh/mix-pulldown-refresh';
	import mixLoadMore from '@/components/mix-load-more/mix-load-more';
	let windowWidth = 0,
		scrollTimer = false,
		tabBar;
	import {
		DOMParser
	} from 'xmldom'
	export default {
		components: {
			mixPulldownRefresh,
			mixLoadMore,
		},
		data() {
			return {
				content: null,
				tabCurrentIndex: 0, //当前选项卡索引
				scrollLeft: 0, //顶部选项卡左滑距离
				enableScroll: true,
				tabBars: [],
				modalName:null,
				
				
			}
		},
		computed: {

		},
		async onLoad() {
			// 获取屏幕宽度
		
			windowWidth = uni.getSystemInfoSync().windowWidth;
			
			uni.$on('load', this.loadTabbars)
			this.loadTabbars();
		},
		onReady() {
			// #ifndef MP

		
			// #endif
		},
		methods: {
			textInput(e) {

				this.content = e.detail.value

			},
			showModal(e) {
				this.modalName = e.currentTarget.dataset.target
			},
			hideModal(e) {
				this.modalName = null
			},backup(){
				
				uni.navigateTo({
					url:'../copy/copy'
				})
			},
				
			nav2hot(){
				uni.navigateTo({
					url:'../index/index'
				})
				
			},
			
		
			loadTabbars() {
				var _this = this


				// 		this.$api.getType().then((res)=>{
				// var value = uni.getStorageSync('rssAddress');
				// console.log(value)
				var value =uni.getStorageSync('rssAddrss');
				console.log(123213321)
				console.log(value)
				var tabList = JSON.parse(value)

				tabList.forEach(item => {
					item.newsList = [];
					item.loadMoreStatus = 0; //加载更多 0加载前，1加载中，2没有更多了
					item.refreshing = 0;
					item.page = -1
				})
				_this.tabBars = tabList;
				_this.loadNewsList('add');


			},
		
			//新闻列表
			loadNewsList(type) {
				let tabItem = this.tabBars[this.tabCurrentIndex];

				//type add 加载更多 refresh下拉刷新
				if (type === 'add') {
					if (tabItem.loadMoreStatus === 2) {
						return;
					}
					tabItem.loadMoreStatus = 1;
					tabItem.page = tabItem.page + 1
				}
				// #ifdef APP-PLUS
				else if (type === 'refresh') {
					tabItem.refreshing = true;
				}
				// #endif



				for(var i =0;i<this.tabBars.length;i++){

									  if(i!=this.tabCurrentIndex && i!=this.tabCurrentIndex-1 && i!=this.tabCurrentIndex+1){
										  //只保留左右侧缓存

										let itemCache = this.tabBars[i]
										itemCache.newsList = [];
										itemCache.loadMoreStatus = 0;  //加载更多 0加载前，1加载中，2没有更多了
										itemCache.refreshing = 0;
										itemCache.page = -1
										itemCache.loaded = false
									  }
				}

				let list = null;


				this.$api.getRssHub(tabItem.url).then((res) => {

					tabItem.newsList = []
					const doc = new DOMParser().parseFromString(res.data, 'text/xml')
					var d = doc.documentElement.getElementsByTagName("item")
					for (var i = 0; i < d.length; i++) {
						var item = {}
						var des = d[i].childNodes[3].firstChild.data
						var reg = /<[^<>]+>/g;//1、全局匹配g肯定忘记写,2、<>标签中不能包含标签实现过滤HTML标签
                        item['txt'] = d[i].childNodes[3].firstChild.data.replace(reg, '');//替换HTML标签

						
						// var srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i;
						// var arr = des.match(imgReg);
						let title = d[i].getElementsByTagName("title")[0]
						if(title){
							if(title.firstChild ){
								item['title'] = d[i].getElementsByTagName("title")[0].firstChild.data
							}
							
						}
						
						let des = d[i].getElementsByTagName("description")[0]
						if(des){
							if(des.firstChild){
								item['des'] = des.firstChild.data
							}
							
						}
						
						let time =  d[i].getElementsByTagName("pubDate")[0]
						if(time){
							if(time.firstChild){
								item['time']  = time.firstChild.data
							}
							
						}
						
						
						let link = d[i].getElementsByTagName("link")[0]
						
						if(link){
							if(link.firstChild){
								item['Url'] = link.firstChild.data
							}
						}
						
						
						tabItem.newsList.push(item)
					}
					tabItem.loadMoreStatus = 2

				})

				if (type === 'refresh') {
					tabItem.newsList = []; //刷新前清空数组
				}
				// list.forEach(item=>{

				// 	tabItem.newsList.push(item);
				// })
				//下拉刷新 关闭刷新动画
				if (type === 'refresh') {
					this.$refs.mixPulldownRefresh && this.$refs.mixPulldownRefresh.endPulldownRefresh();
					// #ifdef APP-PLUS
					tabItem.refreshing = false;
					// #endif
					tabItem.loadMoreStatus = 0;
				}
				
				
				
			},
			//新闻详情
			navToDetails(item) {
				
					let data = {
						
						title: item.title,
						time: item.time,
						des:item.des,
						Url:item.Url
					}
					help.info = data
					
					uni.navigateTo({
						url: `/pages/details/videoDetails`
					})
				
				// window.open(item.Url, '_blank');
			},

			//下拉刷新
			onPulldownReresh() {
				this.loadNewsList('refresh');
			},
			//上滑加载
			loadMore() {
				this.loadNewsList('add');
			},
			//设置scroll-view是否允许滚动，在小程序里下拉刷新时避免列表可以滑动
			setEnableScroll(enable) {
				if (this.enableScroll !== enable) {
					this.enableScroll = enable;
				}
			},
			tapType(item) {
				this.curTab = item
				this.tabCurrentIndex = 0,
					this.loadTabbars()
				this.modalName = null
			},

			//tab切换
			async changeTab(e) {

				if (scrollTimer) {
					//多次切换只执行最后一次
					clearTimeout(scrollTimer);
					scrollTimer = false;
				}
				let index = e;
				//e=number为点击切换，e=object为swiper滑动切换
				if (typeof e === 'object') {
					index = e.detail.current
				}
				if (typeof tabBar !== 'object') {
					tabBar = await this.getElSize("nav-bar")
				}
				//计算宽度相关
				let tabBarScrollLeft = tabBar.scrollLeft;
				let width = 0;
				let nowWidth = 0;
				//获取可滑动总宽度
				for (let i = 0; i <= index; i++) {
					let result = await this.getElSize('tab' + i);
					width += result.width;
					if (i === index) {
						nowWidth = result.width;
					}
				}
				if (typeof e === 'number') {
					//点击切换时先切换再滚动tabbar，避免同时切换视觉错位
					this.tabCurrentIndex = index;
				}
				//延迟300ms,等待swiper动画结束再修改tabbar
				scrollTimer = setTimeout(() => {
					if (width - nowWidth / 2 > windowWidth / 2) {
						//如果当前项越过中心点，将其放在屏幕中心
						this.scrollLeft = width - nowWidth / 2 - windowWidth / 2;
					} else {
						this.scrollLeft = 0;
					}
					if (typeof e === 'object') {
						this.tabCurrentIndex = index;
					}
					this.tabCurrentIndex = index;


					//第一次切换tab，动画结束后需要加载数据
					let tabItem = this.tabBars[this.tabCurrentIndex];
					if (tabItem.loaded !== true) {
						this.loadNewsList('add');
						tabItem.loaded = true;
					}
				}, 300)

			},
			nav2Add(){
				uni.navigateTo({
					url:'../addRss/addRss'
				})
			},
			//获得元素的size
			getElSize(id) {
				return new Promise((res, rej) => {
					let el = uni.createSelectorQuery().select('#' + id);
					el.fields({
						size: true,
						scrollOffset: true,
						rect: true
					}, (data) => {
						res(data);
					}).exec();
				});
			},
			search(e) {
				uni.navigateTo({
					url: `/pages/details/details?data=${this.content}`
				})
			},
			tapRss() {
				uni.navigateTo({
					url:'../magRss/magRss'
				})
			}
		}
	}
</script>

<style lang='scss'>
	page,
	 {

		height: 100%;

	}
	
	/* 顶部tabbar */
	.nav-bar {

		position: relative;
		z-index: 10;
		height: 90upx;
		white-space: nowrap;
		box-shadow: 0 2upx 8upx rgba(0, 0, 0, .06);
		background-color: #fff;

		.nav-item {
			text-overflow: ellipsis;
			overflow: hidden;
			display: inline-block;
			width: 150upx;
			height: 90upx;
			text-align: center;
			line-height: 90upx;
			font-size: 30upx;
			color: #303133;
			position: relative;

			&:after {
				content: '';
				width: 0;
				height: 0;
				border-bottom: 4upx solid #007aff;
				position: absolute;
				left: 50%;
				bottom: 0;
				transform: translateX(-50%);
				transition: .3s;
			}
		}

		.current {
			color: #007aff;

			&:after {
				width: 50%;
			}
		}
	}

	.swiper-box {
		height: 100%;
	}

	.panel-scroll-box {
		height: 100%;

		.panel-item {
			background: #fff;
			padding: 30px 0;
			border-bottom: 2px solid #000;
		}
	}

	.DrawerPage {
		position: fixed;
		width: 100vw;
		height: 100vh;
		left: 0vw;
		background-color: #f1f1f1;
		transition: all 0.4s;
	}

	.DrawerPage.show {
		transform: scale(0.9, 0.9);
		left: 85vw;
		box-shadow: 0 0 60upx rgba(0, 0, 0, 0.2);
		transform-origin: 0;
	}

	.DrawerWindow {
		position: absolute;
		width: 85vw;
		height: 100vh;
		left: 0;
		top: 0;
		transform: scale(0.9, 0.9) translateX(-100%);
		opacity: 0;
		pointer-events: none;
		transition: all 0.4s;
		padding: 100upx 0;
	}

	.DrawerWindow.show {
		transform: scale(1, 1) translateX(0%);
		opacity: 1;
		pointer-events: all;
	}

	.DrawerClose {
		position: absolute;
		width: 40vw;
		height: 100vh;
		right: 0;
		top: 0;
		color: transparent;
		padding-bottom: 30upx;
		display: flex;
		align-items: flex-end;
		justify-content: center;
		background-image: linear-gradient(90deg, rgba(0, 0, 0, 0.01), rgba(0, 0, 0, 0.6));
		letter-spacing: 5px;
		font-size: 50upx;
		opacity: 0;
		pointer-events: none;
		transition: all 0.4s;
	}

	.DrawerClose.show {
		opacity: 1;
		pointer-events: all;
		width: 15vw;
		color: #fff;
	}

	.DrawerPage .cu-bar.tabbar .action button.cuIcon {
		width: 64upx;
		height: 64upx;
		line-height: 64upx;
		margin: 0;
		display: inline-block;
	}

	.DrawerPage .cu-bar.tabbar .action .cu-avatar {
		margin: 0;
	}

	.DrawerPage .nav {
		flex: 1;
	}

	.DrawerPage .nav .cu-item.cur {
		border-bottom: 0;
		position: relative;
	}

	.DrawerPage .nav .cu-item.cur::after {
		content: "";
		width: 10upx;
		height: 10upx;
		background-color: currentColor;
		position: absolute;
		bottom: 10upx;
		border-radius: 10upx;
		left: 0;
		right: 0;
		margin: auto;
	}

	.DrawerPage .cu-bar.tabbar .action {
		flex: initial;
	}
</style>
